<template>
  <el-drawer
    v-model="renderVisible"
    :title="props.title"
    destroy-on-close
    :size="props.size"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form
      ref="formRef"
      :label-position="'top'"
      label-width="100px"
      :model="formData"
      :rules="formRules"
    >
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="formData.name" :disabled="props.isEdit"></el-input>
      </el-form-item>
      <el-form-item label="角色别名" prop="label">
        <el-input v-model="formData.label"></el-input>
      </el-form-item>
      <el-form-item label="权限" prop="perIds">
        <el-tree
          ref="treeRef"
          :data="treeOpts.data"
          node-key="id"
          show-checkbox
          check-strictly
          check-on-click-node
          default-expand-all
          :default-checked-keys="treeOpts.value"
          :props="treeOpts.props"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <PipeResetBtn :formEl="formRef">重置</PipeResetBtn>
      <el-button
        type="primary"
        @click="handleClickSubmit(formRef)"
        :loading="isLoading"
        >提交</el-button
      >
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { reactive, ref, watch, computed, PropType } from 'vue';
import type { ElForm, ElTree } from 'element-plus';
import { ElMessage } from 'element-plus';
import { addRole, updateRole } from '@/apis/role';
import { getPermissionTree } from '@/apis/permission';
import * as _ from 'lodash';
import { loopPropAssignment } from '@/utils/util';

interface FormData {
  name: string;
  label: string;
  perIds: string;
}

// tree refs
const treeRef = ref<InstanceType<typeof ElTree>>();

// tree数据
const treeOpts = reactive({
  // tree的映射名
  props: {
    children: 'children',
    label: 'title'
  },
  data: [] as API.permission.TreeSchema[],
  // 选中的节点ids
  value: []
});

// 加载状态
const isLoading = ref(false);

// 表单ref
const formRef = ref<InstanceType<typeof ElForm>>();

// 表单数据
const formData: FormData = reactive({
  name: '',
  label: '',
  perIds: ''
});

// watch(
//   () => props.rowData,
//   (val, oldVal) => {
//     formData.id = val.id;
//     formData.name = val.name;
//     formData.perIds = val.perIds;

//     if (val.perIds) {
//       // 解析perIds
//       treeOpts.value = val.perIds.split(",");
//     } else {
//       treeOpts.value = [];
//     }
//   },
//   {
//     deep: true,
//     immediate: true,
//   }
// );

const formRules = reactive({
  name: [
    { type: 'string', required: true, message: '请输入角色名称' },
    { max: 16, trigger: 'blur', message: '长度不能超过16位字符' }
  ]
});

// props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },

  title: String,

  size: {
    type: [String, Number],
    default: '30%'
  },

  isEdit: {
    type: Boolean,
    default: false
  },

  rowData: {
    // type: Object as PropType<TempsPost>,
    type: Object as PropType<API.role.EntitySchema>,
    default: () => ({})
  }
});

// emits
const emits = defineEmits(['update:modelValue', 'onRefresh']);

// computed - 抽屉[显示|隐藏]
const renderVisible = computed({
  get: () => props.modelValue,
  set: (val) => {
    emits('update:modelValue', val);
  }
});

// watch
watch(
  () => props.modelValue,
  (val) => {
    if (!val) return;

    // 当rowData发生变化，初始化数据
    loopPropAssignment(formData, props.rowData);

    if (props.rowData.perIds) {
      // 解析perIds
      treeOpts.value = props.rowData.perIds.split(',') as any;
    } else {
      treeOpts.value = [];
    }
  },
  {
    immediate: true
  }
);

// btn - submit
const handleClickSubmit = (formEl: InstanceType<typeof ElForm> | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (!valid) return;

    // 获取perIds
    const perIds = treeRef.value!.getCheckedKeys(false);
    formData.perIds = perIds.join(',');
    if (props.isEdit) {
      submitDataUpdate(props.rowData.id);
    } else {
      submitDataAdd();
    }
  });
};

// submit - add
const submitDataAdd = () => {
  isLoading.value = true;
  addRole(formData)
    .then((res) => {
      isLoading.value = false;
      ElMessage.success(res.message);
      // 关闭弹窗
      emits('onRefresh');
      renderVisible.value = false;
    })
    .catch(() => {
      isLoading.value = false;
    });
};

// submit - update
const submitDataUpdate = (id: number) => {
  isLoading.value = true;
  updateRole(id, formData)
    .then((res) => {
      isLoading.value = false;
      ElMessage.success(res.message);
      // 关闭弹窗
      emits('onRefresh');
      renderVisible.value = false;
    })
    .catch(() => {
      isLoading.value = false;
    });
};

// 获取权限tree
getPermissionTree().then((res) => {
  treeOpts.data = res.data;
});
</script>

<style lang="scss" scoped></style>
